<template>
  <!-- 个人账号登录 -->
  <div v-if="passwordOption == passwordWay.ACCOUNT_PASSWORD">
    <div :class="{ 'force-div': validaErrorStatus.account }">
      <je-input
        v-model:value="userState.username"
        :placeholder="loginVerify"
        autocomplete="false"
        class="input-item"
        :style="{
          height:
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
          'line-height':
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
          border: validaErrorStatus.account ? '1px solid #ff625c' : '',
        }"
        @keydown.stop="keyDowns(event)"
        @change="changeInfo('account')"
        @blur="changeInfo('account')"
      >
        <template #prefix>
          <i class="fal fa-tablet-android-alt" style="padding-right: 5px"></i>
        </template>
      </je-input>
    </div>
    <div :class="{ 'force-div': validaErrorStatus.password }">
      <je-password
        v-model:value="userState.passwordStr"
        :placeholder="handle.passwordPlace"
        autocomplete="false"
        class="input-item"
        :style="{
          'margin-top':
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '30px' : '30px',
          height:
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
          'line-height':
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
          border: validaErrorStatus.password ? '1px solid #ff625c' : '',
        }"
        @keydown.stop="keyDowns(event)"
        @change="changeInfo('password')"
        @blur="changeInfo('password')"
      >
        <template #prefix>
          <i class="fal fa-lock" style="padding-right: 5px"></i>
        </template>
      </je-password>
    </div>
  </div>
  <!-- 动态密码登录 -->
  <div v-if="passwordOption == passwordWay.DYNAMIC_PASSWORD">
    <div :class="{ 'force-div': validaErrorStatus.phone }">
      <je-input
        v-model:value="userPhone.phone"
        :placeholder="handle.phonePlace"
        :maxlength="11"
        class="input-item"
        :style="{
          height:
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
          'line-height':
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
          border: validaErrorStatus.phone ? '1px solid #ff625c' : '',
        }"
        @change="changeInfo('phone')"
        @blur="changeInfo('phone')"
      >
        <template #prefix>
          <i class="fal fa-tablet-android-alt" style="padding-right: 5px"></i>
        </template>
      </je-input>
    </div>
    <div :class="{ 'force-div': validaErrorStatus.authCode }">
      <je-input
        v-model:value="userPhone.authCode"
        :placeholder="handle.authCodePlace"
        class="input-item"
        :style="{
          'margin-top':
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '30px' : '30px',
          height:
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
          'line-height':
            configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
          border: validaErrorStatus.authCode ? '1px solid #ff625c' : '',
        }"
        @change="changeInfo('authCode')"
        @blur="changeInfo('authCode')"
      >
        <template #prefix>
          <i class="jeicon jeicon-key" style="padding-right: 5px"></i>
        </template>
        <template #suffix>
          <span
            :class="{ 'auth-code': sendCodeStatus, 'auth-time': !sendCodeStatus }"
            @click="sendAuthCode"
            >{{ sendCodeStatus ? handle.getAuthCode : sendCountdown + 's' }}</span
          >
        </template>
      </je-input>
    </div>
  </div>
  <!-- <PuzzleSlider
    :bind="$attrs"
    :show="isShow"
    success-text="验证成功"
    fail-text="验证失败"
    slider-text="拖动滑块完成拼图"
    @success="success"
    @close="close"
  /> -->
  <div
    v-if="
      passwordOption == passwordWay.ACCOUNT_PASSWORD ||
      passwordOption == passwordWay.DYNAMIC_PASSWORD
    "
  >
    <div class="operate-box">
      <je-switch
        v-model:value="rememberState"
        class="opera-status"
        mode="checkbox"
        :label="handle.statusLabel"
      />
      <div v-if="configOption.JE_CORE_PHONEREPASSWORD == 1" class="opera-item">
        <span class="sepa-line">|</span>
        <span class="opera-name" @click="handleForget">{{ handle.forgetLable }}</span>
      </div>
      <div v-if="configOption.JE_CORE_PHONELOGIN == 1">
        <span class="sepa-line">|</span>
        <span class="opera-name" @click="switchCodeWay">
          {{
            passwordOption == passwordWay.ACCOUNT_PASSWORD
              ? handle.dynamicLabel
              : handle.personLabel
          }}
        </span>
      </div>
    </div>
    <div
      class="err-tip"
      :style="{
        'margin-top':
          configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '30px' : '30px',
      }"
    >
      {{ errMessage }}
    </div>
    <je-button
      block
      class="login-btn"
      :style="{
        'margin-top':
          configOption.JE_SYS_LOGINMETHOD == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '10px' : '10px',
      }"
      @click="handleLogin"
    >
      <i v-show="!handleFlag" class="jeicon jeicon-circle-notch login-loading"></i>
      <span>{{ handle.loginBtn }}</span>
    </je-button>
  </div>
  <!-- 多部门选择 -->
  <div v-if="passwordOption == passwordWay.MULTIPLE_DEPART">
    <div class="depart-title">{{ handle.departTitle }}</div>
    <div class="depart-box">
      <div
        v-for="departItem in departList"
        :key="departItem.id"
        class="depart-item"
        @click="handleDepart(departItem.id)"
      >
        {{ departItem.name }}
      </div>
    </div>
    <div class="err-tip mar-top">{{ errMessage }}</div>
    <div class="back-login" @click="handleBackLogin">{{ handle.backLogin }}</div>
  </div>
  <!-- 多租户登陆 -->
  <div v-if="passwordOption == passwordWay.MULTIPLE_TENANT">
    <div class="depart-title">{{ handle.tenantTitle }}</div>
    <div class="depart-box">
      <div
        v-for="tenantItem in tenantList"
        :key="tenantItem.id"
        class="depart-item"
        @click="handleTenant(tenantItem.id)"
      >
        {{ tenantItem.name }}
      </div>
    </div>
    <div class="err-tip mar-top">{{ errMessage }}</div>
    <div class="back-login" @click="handleBackLogin">{{ handle.backLogin }}</div>
  </div>
  <!-- 登录后验证是否需要修改密码 -->
  <div v-if="updtatePasswordVisible">
    <update-password
      :visible="updtatePasswordVisible"
      :update-title="updateTitle"
      @closeModal="closeUpdateModal"
      @changeLogin="changeLoginPage"
    />
  </div>
</template>

<script>
  import {
    defineComponent,
    reactive,
    toRefs,
    ref,
    nextTick,
    onMounted,
    onBeforeUnmount,
    watch,
    onBeforeMount,
  } from 'vue';
  import { useI18n } from '@common/locales';
  import VueEvent from '@/helper/event';
  import {
    LOGIN_PLAN,
    EVENT_METHOD,
    LOGIN_PASSWORD_WAY,
    LOGIN_DEVICE,
    SEND_CODE_TIMES,
    SUBMIT_TYPE,
    USER_LOGIN_VERIFY,
    CUR_PAGE,
    DEPTMENT_USER_ID,
  } from '@/helper/constant';
  import { loginValidaPhone, decryptByBase64 } from '@/helper/publish';
  import UpdatePassword from '@/views/login/components/update-password.vue';
  import { Input, Button, Switch } from '@jecloud/ui';
  import { AccountLogin, LoginSendCode, DynamicNodeLogin, checkAccount } from '@/api';
  import { login } from '@common/helper/system';
  import { useGlobalStore } from '@common/store/global-store';
  import { decode, cookie, isNotEmpty, getCurrentUser } from '@jecloud/utils';
  export default defineComponent({
    name: 'LoginAccount',
    components: {
      JeInput: Input,
      JePassword: Input.Password,
      JeSwitch: Switch,
      JeButton: Button,
      UpdatePassword,
      // PuzzleSlider,
    },
    setup() {
      const globalStore = useGlobalStore();
      const t = useI18n().t;
      let configOption = ref({ JE_SYS_LOGINMETHOD: LOGIN_PLAN.MARK_LOGIN_LOGINMETHOD_1 });
      let passwordOption = ref(LOGIN_PASSWORD_WAY.ACCOUNT_PASSWORD); //密码登录方式
      sessionStorage.setItem('temLoginWay', LOGIN_PASSWORD_WAY.ACCOUNT_PASSWORD);
      // let passwordOption = ref(LOGIN_PASSWORD_WAY.MULTIPLE_DEPART);
      let temLoginWay = LOGIN_PASSWORD_WAY.ACCOUNT_PASSWORD; //临时登录方式
      let sendCodeStatus = ref(true); //验证码发送状态
      let authCodeTimeout = SEND_CODE_TIMES; //短信验证码有效时间 默认时间
      let sendCountdown = ref(authCodeTimeout);
      let errMessage = ref(''); //验证错误消息提醒
      let isShow = ref(false); //是否显示图片验证
      let rememberCache = localStorage.getItem('remberStatus')
        ? localStorage.getItem('remberStatus').toString()
        : '0';
      let rememberState = ref(rememberCache); //记住状态
      let loginVerify = ref(''); //用户能够登录的方式
      let handleFlag = ref(true); //是否可以操作标识符
      const userState = reactive({
        username: localStorage.getItem('userName') ? localStorage.getItem('userName') : '',
        passwordStr: localStorage.getItem('userPassword')
          ? localStorage.getItem('userPassword')
          : '',
      });
      const userPhone = reactive({
        phone: localStorage.getItem('userPhone') ? localStorage.getItem('userPhone') : '',
        authCode: '',
      });
      const slideImgs = reactive([]);
      //验证错误状态
      const validaErrorStatus = reactive({
        account: false,
        password: false,
        phone: false,
        authCode: false,
      });
      let sentObj = {
        //发送验证码定时器
        sentCodeTimer: null,
        sentCodeTime: 1000,
      };
      const state = reactive({
        loginPlan: LOGIN_PLAN,
        eventMethod: EVENT_METHOD,
        passwordWay: LOGIN_PASSWORD_WAY,
        departList: [], //多部门列表
        tenantList: [], //多租户列表
        handle: {
          statusLabel: t('accountLogin.remeberStatus'),
          forgetLable: t('accountLogin.forgetPass'),
          dynamicLabel: t('accountLogin.dynamicPass'),
          personLabel: t('accountLogin.personPass'),
          loginBtn: t('accountLogin.enter'),
          userNamePlace: t('accountLogin.userNamePlace'),
          passwordPlace: t('accountLogin.passwordPlace'),
          phonePlace: t('accountLogin.phonePlace'),
          authCodePlace: t('accountLogin.authCodePlace'),
          getAuthCode: t('accountLogin.getAuthCode'),
          emptyAccount: t('warnMessage.account'),
          emptyPassword: t('warnMessage.password'),
          emptyPhone: t('warnMessage.phone'),
          emptyAuthCode: t('warnMessage.authCode'),
          formatPhone: t('warnMessage.formatPhone'),
          backLogin: t('resetPassword.backLogin'),
          departTitle: t('depart.title'),
          tenantTitle: t('tenant.title'),
        },
        updtatePasswordVisible: false, //强制修改密码弹窗
        updateTitle: '', //强制修改密码标题
        curTenantId: '', //当前租户id
      });
      const methods = {
        triggerConfig(data) {
          nextTick(() => {
            //监听登录页面配置信息
            configOption.value = { ...data };
            methods.fromatVerify(data.JE_CORE_VERIFY);
            authCodeTimeout = parseInt(data.JE_SMS_TIMEOUT);
            sendCountdown.value = authCodeTimeout;
          });
        },
        fromatVerify(verifyStr) {
          //转换登录信息
          let loginMethods = verifyStr.split(',');
          let temLogin = [];
          for (let item of loginMethods) {
            if (item in USER_LOGIN_VERIFY) {
              temLogin.push(USER_LOGIN_VERIFY[item]);
            }
          }
          loginVerify.value = temLogin.join('/');
        },
        sendAuthCode() {
          //获取验证码
          if (!userPhone.phone) {
            errMessage.value = state.handle.emptyPhone;
            return;
          } else {
            if (!loginValidaPhone.test(userPhone.phone)) {
              errMessage.value = state.handle.formatPhone;
              return;
            }
          }
          if (sendCodeStatus.value) {
            LoginSendCode({
              phone: userPhone.phone,
              device: LOGIN_DEVICE,
            }).then((res) => {
              if (res.code == 1000 && res.success) {
                sendCodeStatus.value = !sendCodeStatus.value;
                if (sentObj.sentCodeTimer) {
                  clearInterval(sentObj.sentCodeTimer);
                }
                sentObj.sentCodeTimer = setInterval(() => {
                  sendCountdown.value -= 1;
                  if (sendCountdown.value === 0) {
                    sendCodeStatus.value = true;
                    // sendCountdown.value = SEND_CODE_TIMES;
                    sendCountdown.value = authCodeTimeout;
                    clearInterval(sentObj.sentCodeTimer);
                  }
                }, sentObj.sentCodeTime);
              } else {
                errMessage.value = res.message;
              }
            });
          }
        },
        resetUserInfo() {
          //重置用户信息
          userState.username = '';
          userState.passwordStr = '';
          userPhone.phone = '';
          userPhone.authCode = '';
          errMessage.value = '';
          if (sentObj.sentCodeTimer) {
            clearInterval(sentObj.sentCodeTimer);
          }
          sendCodeStatus.value = true;
          sendCountdown.value = authCodeTimeout;
          for (let key in validaErrorStatus) {
            validaErrorStatus[key] = false;
          }
        },
        switchCodeWay() {
          //密码登录方式切换
          passwordOption.value =
            passwordOption.value === state.passwordWay.ACCOUNT_PASSWORD
              ? state.passwordWay.DYNAMIC_PASSWORD
              : state.passwordWay.ACCOUNT_PASSWORD;
          temLoginWay = passwordOption.value;
          sessionStorage.setItem('temLoginWay', temLoginWay);
          // methods.resetUserInfo();
        },
        handleForget() {
          //忘记密码 FORGET_PASSWORD
          // methods.resetUserInfo();
          sessionStorage.setItem('temLoginWay', state.passwordWay.ACCOUNT_PASSWORD);
          passwordOption.value = state.passwordWay.ACCOUNT_PASSWORD;
          VueEvent.emit(state.eventMethod.FORGET_PASSWORD);
        },
        handleLogin() {
          //登录
          if (passwordOption.value != LOGIN_PASSWORD_WAY.MULTIPLE_DEPART) {
            switch (sessionStorage.getItem('temLoginWay')) {
              case state.passwordWay.ACCOUNT_PASSWORD:
                if (!userState.username) {
                  validaErrorStatus.account = true;
                  errMessage.value = state.handle.emptyAccount;
                  return;
                } else {
                  validaErrorStatus.account = false;
                  errMessage.value = '';
                }
                if (!userState.passwordStr) {
                  validaErrorStatus.password = true;
                  errMessage.value = state.handle.emptyPassword;
                  return;
                } else {
                  validaErrorStatus.password = false;
                  errMessage.value = '';
                }
                if (userState.username && userState.passwordStr && handleFlag.value) {
                  handleFlag.value = false;
                  AccountLogin({
                    account: userState.username,
                    password: userState.passwordStr,
                    device: LOGIN_DEVICE,
                  }).then((res) => {
                    methods.checkoutLoginInfo(res, SUBMIT_TYPE.SUBMIT_LOGIN);
                  });
                }
                break;
              case state.passwordWay.DYNAMIC_PASSWORD:
                if (!userPhone.phone) {
                  validaErrorStatus.phone = true;
                  errMessage.value = state.handle.emptyPhone;
                  return;
                } else {
                  if (!loginValidaPhone.test(userPhone.phone)) {
                    errMessage.value = state.handle.formatPhone;
                    return;
                  }
                  validaErrorStatus.phone = false;
                  errMessage.value = '';
                }
                if (!userPhone.authCode) {
                  validaErrorStatus.authCode = true;
                  errMessage.value = state.handle.emptyAuthCode;
                  return;
                } else {
                  validaErrorStatus.authCode = false;
                  errMessage.value = '';
                }
                //动态密码登录
                if (handleFlag.value) {
                  handleFlag.value = false;
                  DynamicNodeLogin({
                    phone: userPhone.phone,
                    captcha: userPhone.authCode,
                    device: LOGIN_DEVICE,
                  }).then((res) => {
                    methods.checkoutLoginInfo(res, SUBMIT_TYPE.SUBMIT_LOGIN);
                  });
                }
                break;
              default:
                break;
            }
          }
        },
        resetData() {
          //重置登录数据
          userState.username = '';
          userState.passwordStr = '';
          userPhone.phone = '';
          userPhone.authCode = '';
        },
        checkoutLoginInfo(res, type) {
          switch (res.code) {
            case '1000': //登录成功
              //判断cookie是否存在select、info、code、account数据
              cookie.get('select') && cookie.remove('select');
              cookie.get('info') && cookie.remove('info');
              cookie.get('code') && cookie.remove('code');
              cookie.get('account') && cookie.remove('account');
              if (type === SUBMIT_TYPE.SUBMIT_LOGIN) {
                localStorage.setItem('authorization', res.data);
                const token = res.data;
                // 放入cookie
                globalStore.setToken(token);
                switch (sessionStorage.getItem('temLoginWay')) {
                  case state.passwordWay.ACCOUNT_PASSWORD:
                    if (rememberState.value === '0') {
                      localStorage.removeItem('userName');
                      localStorage.removeItem('userPassword');
                      localStorage.removeItem('remberStatus');
                      localStorage.removeItem('userPhone');
                    } else {
                      //记住状态
                      localStorage.setItem('userName', userState.username);
                      localStorage.setItem('userPassword', userState.passwordStr);
                      localStorage.setItem('remberStatus', rememberState.value.toString());
                    }
                    break;
                  case state.passwordWay.DYNAMIC_PASSWORD:
                    if (rememberState.value === '0') {
                      localStorage.removeItem('userPhone');
                      localStorage.removeItem('remberStatus');
                      localStorage.removeItem('userName');
                      localStorage.removeItem('userPassword');
                    } else {
                      //记住状态
                      localStorage.setItem('userPhone', userPhone.phone);
                      localStorage.setItem('remberStatus', rememberState.value.toString());
                    }
                    break;
                  default:
                    break;
                }
                handleFlag.value = true;

                checkAccount(token).then((res) => {
                  //检查用户是否需要修改密码
                  if (res.code == 1000 && res.success) {
                    const resData = res.data;
                    if (resData.inited || resData.passwdStrategy) {
                      //需要修改密码
                      if (resData.passwdStrategy) {
                        state.updateTitle = '强制变更密码安全策略';
                      }
                      if (resData.inited) {
                        state.updateTitle = '强制修改默认密码';
                      }
                      state.updtatePasswordVisible = true;
                    } else {
                      //不需要修改密码
                      // 系统登录
                      if (isNotEmpty(cookie.get('url'))) {
                        let routerUrl = decryptByBase64(cookie.get('url'));
                        routerUrl = routerUrl.replace(/^\/#+/, '');
                        globalStore.historyRoute = routerUrl;
                      }
                      login({ token: token });
                      cookie.get('url') && cookie.remove('url');
                      //登录时判断用户所在部门是否与上一次登录部门一致，如不一致，则清空之前缓存的产品信息
                      if (isNotEmpty(getCurrentUser())) {
                        const { deptmentUserId } = getCurrentUser(); //获取当前用户的部门id
                        const userDeptmenId = localStorage.getItem(DEPTMENT_USER_ID);
                        if (userDeptmenId && deptmentUserId) {
                          if (userDeptmenId != deptmentUserId) {
                            localStorage.removeItem(userDeptmenId);
                            localStorage.setItem(DEPTMENT_USER_ID, deptmentUserId);
                          }
                        } else {
                          localStorage.setItem(DEPTMENT_USER_ID, deptmentUserId);
                        }
                      }
                    }
                  }
                });
              }
              break;
            case '5000': //需要选择租户
              state.tenantList = [...res.data]; //多租户列表
              handleFlag.value = true;
              passwordOption.value = LOGIN_PASSWORD_WAY.MULTIPLE_TENANT;
              break;
            case '5001': //需要选择部门
              state.departList = [...res.data];
              handleFlag.value = true;
              passwordOption.value = LOGIN_PASSWORD_WAY.MULTIPLE_DEPART;
              break;
            case '5002': //需要校验验证码
              errMessage.value = res.message;
              handleFlag.value = true;
              break;
            default:
              if (!res.success) {
                errMessage.value = res.message;
                handleFlag.value = true;
              }
              break;
          }
        },
        changeInfo(type) {
          switch (type) {
            case 'account': //监听用户名输入
              if (userState.username) {
                errMessage.value = '';
                validaErrorStatus.account = false;
              } else {
                errMessage.value = state.handle.emptyAccount;
                validaErrorStatus.account = true;
              }
              break;
            case 'password': //监听密码
              if (userState.username) {
                if (userState.passwordStr) {
                  errMessage.value = '';
                  validaErrorStatus.password = false;
                } else {
                  errMessage.value = state.handle.emptyPassword;
                  validaErrorStatus.password = true;
                }
              }
              break;
            case 'phone': //监听手机号
              if (userPhone.phone) {
                errMessage.value = '';
                validaErrorStatus.phone = false;
              } else {
                errMessage.value = state.handle.emptyPhone;
                validaErrorStatus.phone = true;
              }
              break;
            case 'authCode': //监听验证码
              if (userPhone.phone) {
                if (userPhone.authCode) {
                  errMessage.value = '';
                  validaErrorStatus.authCode = false;
                } else {
                  errMessage.value = state.handle.emptyAuthCode;
                  validaErrorStatus.authCode = true;
                }
              }
              break;
            default:
          }
        },
        success(x) {
          isShow.value = false; // 通过验证后，需要手动隐藏模态框
          // this.$emit('success', x);
        },
        // 用户点击遮罩层，应该关闭模态框
        close() {
          isShow.value = false;
          // this.$emit('close');
        },
        fail(x) {
          // this.$emit('fail', x);
        },
        keyDowns(event) {
          const e = event || window.event;
          if (sessionStorage.getItem(CUR_PAGE.temPage) === CUR_PAGE.loginPage) {
            if (e && e.keyCode === 13) {
              nextTick(() => {
                methods.handleLogin();
              });
              e.stopPropagation();
            } else {
              return false;
            }
          }
        },
        handleDepart(departId) {
          //选择对应部门进行登录
          switch (temLoginWay) {
            case state.passwordWay.ACCOUNT_PASSWORD:
              if (handleFlag.value) {
                handleFlag.value = false;
                const loginParam = {
                  account: userState.username,
                  password: userState.passwordStr,
                  device: LOGIN_DEVICE,
                  deptId: departId,
                  tenantId: state.curTenantId,
                };
                //判断cookie是否存在code
                if (isNotEmpty(cookie.get('code'))) {
                  loginParam.code = cookie.get('code');
                }
                //判断cookie是否存在account帐号
                if (isNotEmpty(cookie.get('account'))) {
                  loginParam.account = decryptByBase64(cookie.get('account'));
                }
                AccountLogin(loginParam).then((res) => {
                  methods.checkoutLoginInfo(res, SUBMIT_TYPE.SUBMIT_LOGIN);
                });
              }
              break;
            case state.passwordWay.DYNAMIC_PASSWORD:
              if (handleFlag.value) {
                handleFlag.value = false;
                DynamicNodeLogin({
                  phone: userPhone.phone,
                  captcha: userPhone.authCode,
                  device: LOGIN_DEVICE,
                  deptId: departId,
                  tenantId: state.curTenantId,
                }).then((res) => {
                  methods.checkoutLoginInfo(res, SUBMIT_TYPE.SUBMIT_LOGIN);
                });
              }
              break;
            default:
              break;
          }
        },
        handleTenant(tenantId) {
          //选择多租户
          state.curTenantId = tenantId;
          switch (temLoginWay) {
            case state.passwordWay.ACCOUNT_PASSWORD:
              if (handleFlag.value) {
                handleFlag.value = false;
                AccountLogin({
                  account: userState.username,
                  password: userState.passwordStr,
                  device: LOGIN_DEVICE,
                  tenantId: tenantId,
                }).then((res) => {
                  methods.checkoutLoginInfo(res, SUBMIT_TYPE.SUBMIT_LOGIN);
                });
              }
              break;
            case state.passwordWay.DYNAMIC_PASSWORD:
              if (handleFlag.value) {
                handleFlag.value = false;
                DynamicNodeLogin({
                  phone: userPhone.phone,
                  captcha: userPhone.authCode,
                  device: LOGIN_DEVICE,
                  tenantId: tenantId,
                }).then((res) => {
                  methods.checkoutLoginInfo(res, SUBMIT_TYPE.SUBMIT_LOGIN);
                });
              }
              break;
            default:
              break;
          }
        },
        handleBackLogin() {
          //返回登录
          errMessage.value = '';
          passwordOption.value = temLoginWay;
        },
        closeUpdateModal() {
          //关闭修改密码弹窗
          state.updtatePasswordVisible = false;
        },
        changeLoginPage() {
          //切换到之前登录状态
          passwordOption.value = temLoginWay;
        },
        judgeCookie() {
          //判断cookie中select为true和info,展示多部门登录
          if (
            isNotEmpty(cookie.get('select')) &&
            decode(decryptByBase64(cookie.get('select'))) &&
            isNotEmpty(cookie.get('info'))
          ) {
            state.departList = [...decode(decryptByBase64(cookie.get('info')))];
            handleFlag.value = true;
            passwordOption.value = LOGIN_PASSWORD_WAY.MULTIPLE_DEPART;
            temLoginWay = state.passwordWay.ACCOUNT_PASSWORD; //更改登录方式为帐号密码
          }
        },
      };
      //监听事件
      watch(
        () => rememberState.value,
        (val) => {
          if (val == 0) {
            localStorage.removeItem('remberStatus');
          } else {
            localStorage.setItem('remberStatus', val);
          }
        },
      );
      //监听用户名
      // watch(
      //   () => userState.username,
      //   (newVal, oldVal) => {
      //     if (newVal != oldVal) {
      //       userState.username = newVal;
      //       if (rememberState.value == 1) {
      //         localStorage.setItem('userName', '');
      //       }
      //     }
      //   },
      //   {
      //     deep: true,
      //   },
      // );
      //监听登录密码
      // watch(
      //   () => userState.passwordStr,
      //   (newVal, oldVal) => {
      //     if (newVal != oldVal) {
      //       userState.passwordStr = newVal;
      //       if (rememberState.value == 1) {
      //         localStorage.setItem('userPassword', newVal);
      //       }
      //     }
      //   },
      // );

      onBeforeMount(() => {
        methods.judgeCookie();
      });

      onMounted(() => {
        VueEvent.on(state.eventMethod.LOGIN_METHOD, methods.triggerConfig);
        // document.onkeydown = function (e) {
        //   debugger;
        //   methods.keyDowns(e);
        // };
        // document.addEventListener('keydown', methods.keyDowns, false);
      });
      onBeforeUnmount(() => {
        // document.removeEventListener('keydown', methods.keyDowns);
        VueEvent.off(state.eventMethod.LOGIN_METHOD);
        sessionStorage.removeItem('temLoginWay');
      });
      return {
        configOption,
        passwordOption,
        sendCodeStatus,
        sendCountdown,
        userState,
        userPhone,
        errMessage,
        slideImgs,
        isShow,
        rememberState,
        validaErrorStatus,
        loginVerify,
        handleFlag,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style>
  input:-webkit-autofill,
  textarea:-webkit-autofill,
  select:-webkit-autofill {
    -webkit-text-fill-color: #3f3f3f !important;
    -webkit-box-shadow: 0 0 0px 1000px transparent inset !important;
    background-color: transparent;
    background-image: none;
    transition: background-color 50000s ease-in-out 0s;
  }
  input {
    background-color: transparent;
  }
  .input-item .ant-input-clear-icon {
    top: 12px !important;
  }
  .no-rember .ant-checkbox + span {
    color: #3f3f3f;
  }
  .operate-box .ant-checkbox-inner {
    top: 1px;
  }
  .operate-box .ant-checkbox-checked::after {
    top: 1px;
  }
  .login-btn > i + span {
    margin-left: 0;
    width: 42px;
  }
</style>
<style scoped lang="less">
  .input-item {
    border-radius: 2px;
    font-size: 12px;
    color: #a1a1a1;
    line-height: 46px;
    height: 46px;
  }
  .operate-box {
    width: 100%;
    height: 20px;
    line-height: 20px;
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    font-size: 14px;
    font-family: 'PingFang SC, PingFang SC-Normal';
    .opera-item {
      padding-right: 8px;
    }
    .sepa-line {
      color: #dcdfe6;
      padding-right: 8px;
    }
    .opera-name {
      color: #3f3f3f;
    }
    .opera-name:hover {
      cursor: pointer;
    }
  }
  .err-tip {
    width: 100%;
    height: 20px;
    margin-top: 30px;
    line-height: 20px;
    font-size: 14px;
    color: #ff625c;
    text-align: center;
  }
  .mar-top {
    margin-top: 20px;
  }
  .login-btn {
    width: 100%;
    height: 42px;
    margin-top: 10px;
    font-size: 18px;
    color: #ffffff;
    line-height: 20px;
    font-family: 'PingFang SC, PingFang SC-Normal';
    position: relative;
    text-align: center;
    letter-spacing: 6px;
    .login-loading {
      display: block;
      position: absolute;
      left: 135px;
      top: 13px;
      animation: myloading 1s infinite linear;
    }
    @keyframes myloading {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(359deg);
      }
    }
  }
  .auth-code {
    font-size: 14px;
    color: #3265f5;
    cursor: pointer;
  }
  .auth-time {
    font-size: 14px;
    color: #c0c4cc;
  }
  .depart-title {
    width: 340px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    color: #3f3f3f;
    font-size: 20px;
    font-family: 'PingFang SC, PingFang SC-Normal';
    margin: -20px auto 0;
  }
  .depart-box {
    width: 340px;
    max-height: 240px;
    overflow: auto;
    margin: 20px auto 0;
    .depart-item {
      width: 100%;
      box-sizing: border-box;
      height: 48px;
      line-height: 48px;
      font-size: 16px;
      padding: 0 20px;
      font-family: 'PingFang SC, PingFang SC-Normal';
      color: #3f3f3f;
      border-bottom: 1px solid #f5f5f5;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      cursor: pointer;
    }
  }
  .depart-box::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
  .back-login {
    width: 20%;
    height: 20px;
    line-height: 20px;
    text-align: center;
    color: #3f3f3f;
    font-size: 14px;
    margin: 20px auto 0;
    cursor: pointer;
  }
</style>
